<template>
  <div>
    <Form ref="form" :rules="formValidate" :label-width="90" :model="form">
          <FormItem label="标题" prop="title">
            <Input v-model="form.title" />
          </FormItem>
          <FormItem label="内容" prop="content">
            <Input v-model="form.content" />
          </FormItem>
          <FormItem label="留学地" prop="studyAbroad">
            <Input v-model="form.studyAbroad" />
          </FormItem>
          <FormItem label="专业" prop="specialty">
            <Input v-model="form.specialty" />
          </FormItem>
          <FormItem label="资讯分类" prop="newsTypeId">
            <Select v-model="form.newsTypeId">
                <Option v-for="(newsType) in newsTypeData"
                        :key="newsType.id"
                        :value="newsType.newsTypeCode"
                >{{newsType.newsTypeName}}</Option>
            </Select>
          </FormItem>
    </Form>
    <Row class="code-row-bg" justify="end" type="flex">
      <Button @click="cancel" style="margin-right:10px">取消</Button>
      <Button @click="save" type="primary">保存</Button>
    </Row>
  </div>
</template>
<script>
  import { newsApi } from '@/api/news';
  import { newsTypeApi } from '@/api/news-type';
  import Cookies from 'js-cookie';
  import { TOKEN_KEY } from '@/lib/cookie';
  export default {
    name: 'NewsListForm',
    components: {
    },
    props: {
      //是否为更新表单
      isUpdate: {
        type: Boolean,
        default: true
      },
      //更新的表单数据对象
      updateData: {
        type: Object
      }
    },
    data() {
      return {
        //表单数据
        form: {
         title:null,
         content:null,
         studyAbroad:null,
         specialty:null,
         newsTypeId:null
        },
        //表单验证
        formValidate: {
      
        title:[{ required: true, message: '请输入标题', trigger: 'blur' }],
        content:[{ required: true, message: '请输入内容', trigger: 'blur' }]
        },
        // 图片预览窗口可见
        previewModel: {
          show: false
        },
        newsTypeData:[]
      };
    },
  watch: {
      updateData: function(newValue, oldValue) {
          this.$refs['form'].resetFields();
          if (this.isUpdate) {
              for (let k in this.form) {
                  this.$set(this.form, k, newValue[k]);
              }
              this.$set(this.form, 'id', newValue['id']);
          }
      },
      isUpdate: function(newValue, oldValue) {
          if (!newValue) {
              this.resetForm();
              this.$refs['form'].resetFields();
          }
      }
  },
  computed: {
    uploadHeader: function() {
      let header = {
        'x-access-token': Cookies.get(TOKEN_KEY)
      };
      return header;
    },
    uploadUrl: function() {
      let baseUrl = fileApi.fileUploadLocalUrl;
      let url = baseUrl + 1;
      return url;
    }
  },
    created() {},
    mounted() {
      this.queryNewsType();
    },
    methods: {
      // 上传成功钩子
      async uploadSuccess(e) {
        if (!e.success) {
          console.error(e);
          return this.uploadError();
        }
        this.$Spin.show();
        let reqBody = {
          moduleId: 1,
          moduleType: 1,
          fileLocationType: 1,
          fileName: e.data.fileName,
          filePath: e.data.filePath
        };
        let rep = await fileApi.addFile(reqBody);
        this.form.pictureIds.push(rep.data);
        this.$Spin.hide();
        this.$Message.success('上传成功');
        // this.find();
      },
      // 上传失败钩子
      uploadError(e) {
        this.$Message.error('上传出错，请重试！');
        console.error(e);
        this.find();
      },
      preview(file) {
        this.previewModel.show = true;
        if (this.isUpdate) {
          this.previewModel.imageUrl = file.url;
        } else {
          this.previewModel.imageUrl = file.response.data.url;
        }
      },
      cancel() {
        this.$emit('on-form-close');
      },
      save() {
       this.$refs['form'].validate(valid => {
         if (valid) {
           if (this.isUpdate) {
            this.update();
           } else {
             this.add();
           }
         } else {
          this.$Message.error('参数验证错误，请仔细填写表单数据!');
         }
       });
      },
    resetForm() {
        this.form = {
            title:null,
            content:null,
            studyAbroad:null,
            specialty:null,
            newsTypeId:null
        };
        this.$refs['form'].resetFields();
      },
      async add() {
        this.$Spin.show();
        let res = await newsApi.addNews(this.form);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async update() {
        this.$Spin.show();
        let res = await newsApi.updateNews(this.form);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async queryNewsType() {
        let result = await newsTypeApi.queryAll();
        this.newsTypeData = result.data;
      },
    }
  };
</script>